/**
 * 用户登录API路由
 */
import { NextRequest, NextResponse } from 'next/server';
import { AuthService } from '@/lib/auth';
import { initAuthTables } from '@/lib/db/auth-schema';
import { getDb } from '@/lib/db';

export async function POST(request: NextRequest) {
  try {
    // 确保认证表已初始化
    const db = await getDb();
    await initAuthTables(db);

    const body = await request.json();
    const { emailOrUsername, password } = body;

    // 验证必填字段
    if (!emailOrUsername || !password) {
      return NextResponse.json(
        { error: '邮箱/用户名和密码为必填项', code: 'MISSING_FIELDS' },
        { status: 400 }
      );
    }

    // 获取客户端信息
    const ipAddress = request.headers.get('x-forwarded-for') || 
      request.headers.get('x-real-ip') || 
      'unknown';
    const userAgent = request.headers.get('user-agent') || 'unknown';

    // 执行登录
    const result = await AuthService.login({
      emailOrUsername: emailOrUsername.trim().toLowerCase(),
      password,
      ipAddress,
      userAgent
    });

    if (!result.success) {
      return NextResponse.json(
        { error: result.message, code: 'LOGIN_FAILED' },
        { status: 401 }
      );
    }

    // 设置认证cookie
    const response = NextResponse.json({
      message: result.message,
      user: result.user,
      token: result.token
    });

    // 设置HttpOnly cookie
    if (result.token && result.refreshToken) {
      response.cookies.set('auth-token', result.token, {
        httpOnly: true,
        secure: process.env.NODE_ENV === 'production',
        sameSite: 'lax',
        maxAge: 7 * 24 * 60 * 60 // 7天
      });

      response.cookies.set('refresh-token', result.refreshToken, {
        httpOnly: true,
        secure: process.env.NODE_ENV === 'production',
        sameSite: 'lax',
        maxAge: 30 * 24 * 60 * 60 // 30天
      });
    }

    return response;
  } catch (error) {
    console.error('登录API错误:', error);
    return NextResponse.json(
      { error: '服务器内部错误', code: 'INTERNAL_ERROR' },
      { status: 500 }
    );
  }
}

// 不允许其他HTTP方法
export async function GET() {
  return NextResponse.json(
    { error: '方法不允许', code: 'METHOD_NOT_ALLOWED' },
    { status: 405 }
  );
}